﻿// ParseLib - An open source library for natural language processing.
// Copyright (C) Kais Dukes, 2012. E-mail: kais@kaisdukes.com
// http://parselib.org

using System.Collections.Generic;
using ParseLib.Corpora;
using ParseLib.Experiments;

namespace ParseLib.Tagging
{
    public class TaggingEvaluationMetric : IEvaluationMetric
    {
        private int _validCount;
        private int _expectedCount;

        public void Evaluate(IModel model, IEnumerable<TextualUnit> testData)
        {
            // Initiate.
            _validCount = 0;
            _expectedCount = 0;

            // Evaluate using test data.
            var tagger = (IPartOfSpeechTagger) model;
            foreach (var expected in testData)
            {
                // Tag.
                var actual = expected.CopyText();
                tagger.Tag(actual);

                // Evaluate.
                Evaluate(expected, actual);
            }
        }

        public void Add(IEvaluationMetric metric)
        {
            var taggingMetric = (TaggingEvaluationMetric) metric;
            _validCount += taggingMetric._validCount;
            _expectedCount += taggingMetric._expectedCount;
        }

        public override string ToString()
        {
            var accuracy = _validCount/(double) _expectedCount;
            return string.Format("Accuracy = {0:p}", accuracy);
        }

        private void Evaluate(TextualUnit expected, TextualUnit actual)
        {
            var size = expected.TokenCount;
            for (var i = 0; i < size; i++)
            {
                var expectedToken = expected[i];
                var actualToken = actual[i];

                if (expectedToken.PartOfSpeech == actualToken.PartOfSpeech)
                {
                    _validCount++;
                }
            }

            _expectedCount += size;
        }
    }
}